<template>
  <div class="report-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>销售报表统计</h1>
      <p>实时监控销售数据，助力业务决策</p>
    </div>

    <!-- 日期选择区域 -->
    <div class="date-picker-container">
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :default-value="[new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date()]"
          @change="handleDateChange"
          class="date-picker"
      />
      <el-button
          type="primary"
          @click="fetchReportData"
          :loading="loading"
      >
        <el-icon v-if="loading"><Loading /></el-icon>
        <span>查询数据</span>
      </el-button>
    </div>

    <!-- 图表容器 -->
    <div class="charts-container">
      <!-- 营业额统计图表 -->
      <el-card class="chart-card">
        <div slot="header" class="card-header">
          <h2>营业额统计</h2>
          <p class="total-info">
            总营业额:
            <span class="total-value">{{ turnoverTotal | formatCurrency }}</span>
          </p>
        </div>
        <div class="chart-wrapper">
          <div ref="turnoverChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 用户统计图表 -->
      <el-card class="chart-card">
        <div slot="header" class="card-header">
          <h2>用户统计</h2>
          <p class="total-info">
            总用户数:
            <span class="total-value">{{ userTotal }}</span>
            <span class="separate">|</span>
            新增用户:
            <span class="total-value">{{ newUserTotal }}</span>
          </p>
        </div>
        <div class="chart-wrapper">
          <div ref="userChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 订单统计图表 -->
      <el-card class="chart-card">
        <div slot="header" class="card-header">
          <h2>订单统计</h2>
          <p class="total-info">
            总订单数:
            <span class="total-value">{{ orderTotal }}</span>
            <span class="separate">|</span>
            有效订单:
            <span class="total-value">{{ validOrderTotal }}</span>
            <span class="separate">|</span>
            完成率:
            <span class="total-value">{{ orderCompletionRate | formatPercentage }}</span>
          </p>
        </div>
        <div class="chart-wrapper">
          <div ref="orderChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 销量TOP10图表 -->
      <el-card class="chart-card">
        <div slot="header" class="card-header">
          <h2>销量排名TOP10</h2>
          <p class="total-info">
            统计周期:
            <span class="total-value">{{ dateRange[0] }} 至 {{ dateRange[1] }}</span>
          </p>
        </div>
        <div class="chart-wrapper">
          <div ref="top10Chart" class="chart"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

import * as echarts from 'echarts'
import {
  getTurnoverStatisticsApi,
  getOrdersStatisticsApi,
  getTop10Api,
  getUserStatisticsApi
} from '@/api/report'
import { Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 日期范围
const dateRange = ref([])
// 加载状态
const loading = ref(false)

// 图表实例引用
const turnoverChart = ref(null)
const userChart = ref(null)
const orderChart = ref(null)
const top10Chart = ref(null)

// 图表对象
let turnoverChartObj = null
let userChartObj = null
let orderChartObj = null
let top10ChartObj = null

// 统计数据
const turnoverData = ref({})
const userData = ref({})
const orderData = ref({})  // 对应OrderReportVO
const top10Data = ref({})  // 对应SalesTop10ReportVO

// 总计数据
const turnoverTotal = ref(0)
const userTotal = ref(0)
const newUserTotal = ref(0)
const orderTotal = ref(0)
const validOrderTotal = ref(0)
const orderCompletionRate = ref(0)  // 订单完成率

// 初始化图表
const initCharts = () => {
  turnoverChartObj = echarts.init(turnoverChart.value)
  userChartObj = echarts.init(userChart.value)
  orderChartObj = echarts.init(orderChart.value)
  top10ChartObj = echarts.init(top10Chart.value)

  window.addEventListener('resize', () => {
    turnoverChartObj.resize()
    userChartObj.resize()
    orderChartObj.resize()
    top10ChartObj.resize()
  })
}

// 处理日期范围变化
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    dateRange.value = val
  }
}

// 获取报表據數據
const fetchReportData = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择日期范围')
    return
  }

  const [begin, end] = dateRange.value
  loading.value = true

  try {
    const [turnoverRes, userRes, orderRes, top10Res] = await Promise.all([
      getTurnoverStatisticsApi(begin, end),
      getUserStatisticsApi(begin, end),
      getOrdersStatisticsApi(begin, end),
      getTop10Api(begin, end)
    ])

    // 处理营业额数据
    turnoverData.value = turnoverRes.data
    turnoverTotal.value = turnoverData.value.totalTurnover

    // 处理用户数据
    userData.value = userRes.data
    userTotal.value = userData.value.totalUser
    newUserTotal.value = userData.value.totalNewUser

    // 处理订单数据（适配OrderReportVO）
    orderData.value = orderRes.data
    orderTotal.value = orderData.value.totalOrderCount
    validOrderTotal.value = orderData.value.validOrderCount
    orderCompletionRate.value = orderData.value.orderCompletionRate || 0

    // 处理TOP10数据（适配SalesTop10ReportVO）
    top10Data.value = top10Res.data

    // 更新图表
    updateTurnoverChart()
    updateUserChart()
    updateOrderChart()
    updateTop10Chart()

  } catch (error) {
    console.error('获取报表数据失败', error)
    ElMessage.error('获取报表数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 更新营业额图表
const updateTurnoverChart = () => {
  if (!turnoverChartObj || !turnoverData.value || !turnoverData.value.dateList) return

  // 解析后端返回的逗号分隔字符串为数组
  const dateList = turnoverData.value.dateList ? turnoverData.value.dateList.split(',') : []
  const turnoverList = turnoverData.value.turnoverList ? turnoverData.value.turnoverList.split(',').map(Number) : []

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>营业额: {c} 元'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dateList,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [
      {
        name: '营业额',
        type: 'line',
        data: turnoverList,
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0)' }
          ])
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        }
      }
    ]
  }

  turnoverChartObj.setOption(option)
}

// 更新用户统计图表
const updateUserChart = () => {
  if (!userChartObj || !userData.value || !userData.value.dateList) return

  const dateList = userData.value.dateList ? userData.value.dateList.split(',') : []
  const userList = userData.value.userList ? userData.value.userList.split(',').map(Number) : []
  const newUserList = userData.value.newUserList ? userData.value.newUserList.split(',').map(Number) : []

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let res = params[0].name + '<br/>'
        params.forEach(item => {
          res += `${item.seriesName}: ${item.value}<br/>`
        })
        return res
      }
    },
    legend: {
      data: ['用户总量', '新增用户'],
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      top: '15%'
    },
    xAxis: {
      type: 'category',
      data: dateList,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 个'
      }
    },
    series: [
      {
        name: '用户总量',
        type: 'line',
        data: userList,
        smooth: true,
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '新增用户',
        type: 'line',
        data: newUserList,
        smooth: true,
        itemStyle: {
          color: '#F56C6C'
        },
        lineStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }

  userChartObj.setOption(option)
}

// 更新订单统计图表（适配OrderReportVO）
const updateOrderChart = () => {
  if (!orderChartObj || !orderData.value || !orderData.value.dateList) return

  // 解析后端返回的逗号分隔字符串为数组
  const dateList = orderData.value.dateList ? orderData.value.dateList.split(',') : []
  const orderCountList = orderData.value.orderCountList ? orderData.value.orderCountList.split(',').map(Number) : []
  const validOrderCountList = orderData.value.validOrderCountList ? orderData.value.validOrderCountList.split(',').map(Number) : []

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let res = params[0].name + '<br/>'
        params.forEach(item => {
          res += `${item.seriesName}: ${item.value}<br/>`
        })
        return res
      }
    },
    legend: {
      data: ['订单总数', '有效订单'],
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      top: '15%'
    },
    xAxis: {
      type: 'category',
      data: dateList,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 个'
      }
    },
    series: [
      {
        name: '订单总数',
        type: 'line',
        data: orderCountList,
        smooth: true,
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '有效订单',
        type: 'line',
        data: validOrderCountList,
        smooth: true,
        itemStyle: {
          color: '#F56C6C'
        },
        lineStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }

  orderChartObj.setOption(option)
}

// 更新TOP10图表（适配SalesTop10ReportVO）
const updateTop10Chart = () => {
  if (!top10ChartObj || !top10Data.value || !top10Data.value.nameList) return

  // 解析后端返回的逗号分隔字符串为数组
  const nameList = top10Data.value.nameList ? top10Data.value.nameList.split(',') : []
  const numberList = top10Data.value.numberList ? top10Data.value.numberList.split(',').map(Number) : []

  // 组合数据并按销量降序排列
  const combinedData = nameList.map((name, index) => ({
    name,
    sales: numberList[index] || 0
  })).sort((a, b) => b.sales - a.sales);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>销量: {c}'
    },
    grid: {
      left: '15%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: combinedData.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: 0
      },
      inverse: true
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: combinedData.map(item => item.sales),
        itemStyle: {
          color: function(params) {
            const colorList = ['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399']
            return colorList[Math.floor(params.dataIndex / 2)] || '#909399'
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  }

  top10ChartObj.setOption(option)
}

// 格式化货币过滤器
const formatCurrency = (value) => {
  if (!value) return '0.00'
  return parseFloat(value).toFixed(2)
}

// 格式化百分比过滤器
const formatPercentage = (value) => {
  if (!value) return '0%'
  return (parseFloat(value) * 100).toFixed(2) + '%'
}

// 页面挂载时初始化
onMounted(() => {
  initCharts()
  // 设置默认日期范围为最近7天
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000)

  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]

  // 自动加载数据
  fetchReportData()
})

// 监听图表容器变化，重新调整图表大小
watch([turnoverChart, userChart, orderChart, top10Chart], () => {
  setTimeout(() => {
    turnoverChartObj?.resize()
    userChartObj?.resize()
    orderChartObj?.resize()
    top10ChartObj?.resize()
  }, 0)
})
</script>

<style scoped>
/* 样式保持不变 */
.report-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 30px;
}

.page-title h1 {
  font-size: 24px;
  color: #1f2329;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-title p {
  font-size: 14px;
  color: #6b7280;
}

.date-picker-container {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.date-picker {
  width: 360px;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(600px, 1fr));
  gap: 24px;
}

.chart-card {
  height: 100%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
}

.card-header h2 {
  font-size: 16px;
  color: #1f2329;
  font-weight: 600;
  margin: 0;
}

.total-info {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.total-value {
  color: #1f2329;
  font-weight: 500;
}

.separate {
  color: #d0d5dd;
}

.chart-wrapper {
  padding: 20px;
  height: calc(100% - 65px);
}

.chart {
  width: 100%;
  height: 400px;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media screen and (max-width: 768px) {
  .date-picker-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .date-picker {
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .chart {
    height: 300px;
  }
}
</style>
